import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QSlider, QTextEdit,QHBoxLayout,QLabel,QLineEdit,QWidgetItem,QWidget
from PySide6.QtCore import Qt, QTimer
import sounddevice as sd
from scipy.io.wavfile import write
import scipy.io.wavfile as wavfile
import numpy as np
import time
from AudioPlayerWidget import AudioPlayerWidget
from httpclienttoche import HttpClientToChe
import asyncio
import aiohttp
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("虚拟面试学习机")
        self.initUI()
        self.httpsever=HttpClientToChe()
        self.messages =[{"role": "system", "content": "你是一个虚拟面试学习机，你会根据用户的需求，不停地说面试题目，然后根据面试者的回答，打分并且说出原因"}]
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        #self.messages.append()
        
    def initUI(self):
        # 创建一个垂直布局的容器
        layout1 = QHBoxLayout()
        self.playerWidget = AudioPlayerWidget()
        
        self.playerWidget.loadAudio("audio.mp3")  # 替换为您的音频文件路径
        self.playerWidget.show()
        vlayoutbase = QVBoxLayout()
        vlayout0 = QVBoxLayout()
        vlayout1 = QVBoxLayout()
        self.palne=QWidget()
        self.palne.setFixedSize(150, 600)
        vlayoutbase.addWidget(self.palne)
        layout1.addLayout(vlayoutbase)
        layout1.addLayout(vlayout1)
        self.palne.setLayout(vlayout0)
        # 创建录音按钮，并设置其文字根据状态变化
        self.record_button = QPushButton("录音")
        self.record_button.clicked.connect(self.toggle_record)
        vlayout0 .addWidget(self.record_button)
        vlayout0 .addWidget(self.playerWidget)
        
        hlayout0 =QHBoxLayout()
        vlayout1.addLayout(hlayout0)
        label=QLabel("历史对话")
        hlayout0.addWidget(label)
        # 创建带有滑动条的文本显示框
        self.text_display = QTextEdit()
        self.text_display.setReadOnly(True)
        self.text_display.setStyleSheet("QTextEdit { background-color: rgb(0.0,0.0,155.0); color: rgb(255,255.0,255.0); font-size:16pf }")
        hlayout0 .addWidget(self.text_display)
        hlayout1 =QHBoxLayout()
        vlayout1.addLayout(hlayout1)
        # 创建文本输入框
        label1=QLabel("你的输入")
        hlayout1.addWidget( label1)
        self.text_input = QLineEdit()
        self.send_btn=QPushButton("发送")
        self.send_btn.clicked.connect(self.send_text_input)
        hlayout1.addWidget(self.text_input)
        hlayout1.addWidget( self.send_btn)
        # 设置文本输入框的高度为一行文本的高度
        self.text_input.setFixedHeight(50)
        self.text_input.textChanged.connect(self.text_input_enter)
        # 创建一个中心窗口的小部件
        central_widget = QWidget()
        central_widget.setLayout(layout1 )
        self.setCentralWidget(central_widget)
        # 创建一个状态指示器，用于更新录音按钮的文字
        self.recording = False
        # 创建一个定时器，用于模拟录音过程
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_text)

    def send_text_input(self):   
        content=self.text_input.text()
        self.messages.append({"role": "user", "content": content})
        message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
        self.text_display .setText(message_text)   
        self.text_display .update()
        self.update()
        asyncio.run(self.send_tts(content))
       
        sendmessages=self.messages
        rescentent=self.httpsever.get_chat_completion(sendmessages)  
        self.messages.append({"role": "asstant", "content": rescentent})
        asyncio.run(self.send_tts(rescentent))
        #self.text_display.setText(rescentent)  
        message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
        self.text_display .setText(message_text)   
        self.text_input.setText(" ")
        pass 
    def text_input_enter(self):    
        pass    
    def toggle_record(self):
        self.recording = not self.recording
        if self.recording:
            self.record_button.setText("停止")
            asyncio.run(self.recordasynv())
        else:
            self.record_button.setText("录音")
            self.timer.stop()
            sd.stop()
            fs = 44100  # 采样率
            wavfile.write('record_output.wav', fs, self.audio_data)
            content=self.httpsever.post_audio_transcription('record_output.wav')
            first_choice = content.get('transcription')
            content=first_choice.get('text')
            self.messages.append({"role": "user", "content": content})
            message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
            self.text_display .setText(message_text)   
            self.text_display .update()
            sendmessages=self.messages
            rescentent=self.httpsever.get_chat_completion(sendmessages) 
            asyncio.run(self.send_tts(rescentent)) 
            self.messages.append({"role": "asstant", "content": rescentent})
        #self.text_display.setText(rescentent)  
            message_text = '\n'.join([f"{msg['role']}: {msg['content']}" for msg in self.messages])
            self.text_display .setText(message_text)   
            self.text_input.setText(" ")
            self.audio_data = None
            self.update_text()

    async def recordasynv(self):
        self.timer.start(1000)  # 每秒更新一次文本
            # 设置录音参数
        duration = 30  # 录音时间（秒）
        fs = 44100  # 采样率
        self.audio_data = sd.rec(duration*fs, samplerate=fs, channels=2, dtype='int16')
        #sd.wait()  # 等待录音完成
        print("录音结束。")
        pass
    async def send_tts(self,content):
        self.playerWidget.stop()
        print(content)
        filepath=await self.generate_voice(content)
        self.playerWidget.loadAudio("output.mp3")
        self.playerWidget.play()
        pass
    


    async def generate_voice(self,content):
        filepath=self.httpsever.generate_voice(content)
        return filepath

    def update_text(self):
        if self.recording:
            text = "正在录音...\n" + self.text_display.toPlainText()
        else:
            text = self.text_display.toPlainText()
        self.text_display.setPlainText(text)
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())